package com.lazi.june.common.base;

import com.lazi.june.common.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * desc: ActiveUserHolder
 *
 * @author huliqian
 * @since 2025/8/21
 */
@Slf4j
public class ActiveUserHolder {

    private static final ThreadLocal<ActiveUser> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 判断当前用户是否登录
     *
     * @return Boolean
     */
    public static Boolean isLogin() {
        return THREAD_LOCAL.get() != null;
    }

    /**
     * 获取当前登录用户
     *
     * @return ActiveUser
     */
    public static ActiveUser get() {
        return Optional.ofNullable(THREAD_LOCAL.get())
                .orElseThrow(() -> Result.failed(ExceptionEnum.ERROR_USER_DEFECT_TOKEN));
    }

    /**
     * 获取当前登录用户全局用户ID
     *
     * @return Long
     */
    public static Long getGlobalUserId() {
        return Optional.ofNullable(THREAD_LOCAL.get())
                .map(ActiveUser::getGlobalUserId)
                .orElse( null);
    }

    /**
     * 获取当前登录用户ID
     *
     * @return Long
     */
    public static Long getUserId() {
        return Optional.ofNullable(THREAD_LOCAL.get())
                .map(ActiveUser::getId)
                .orElse( null);
    }


    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static void set(ActiveUser user) {
        THREAD_LOCAL.set(user);
    }

}
